import {Table, Switch, Space, Button, Modal, message, Input} from 'antd';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getProductList, deleteProduct, updateProduct } from '../../services/product';
import {PlusOutlined, SearchOutlined} from "@ant-design/icons";
const { confirm } = Modal;

export default function Product() {
  const [list, setList] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const navigate = useNavigate();
  const [searchKeyword, setSearchKeyword] = useState(''); // 搜索关键词

  const columns = [
    {
      title: '商品ID',
      dataIndex: 'id',
      key: 'id',
      render: (text) => (
          <Button type="link" onClick={() => navigate('/product/' + text)}>
            {text}
          </Button>
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
    },
    {
      title: '浏览量',
      dataIndex: 'views',
      key: 'views',
    },
    {
      title: '销量',
      dataIndex: 'sales',
      key: 'sales',
    },
    {
      title: '是否推荐',
      dataIndex: 'isRecommended',
      key: 'isRecommended',
      render: (isRecommended, record) => (
          <Switch
              checked={isRecommended}
              onChange={(checked) => handleSwitchChange(record.id, 'isRecommended', checked)}
          />
      ),
    },
    {
      title: '是否上架',
      dataIndex: 'isAvailable',
      key: 'isAvailable',
      render: (isAvailable, record) => (
          <Switch
              checked={isAvailable}
              onChange={(checked) => handleSwitchChange(record.id, 'isAvailable', checked)}
          />
      ),
    },
    {
      title: '是否新品',
      dataIndex: 'isNew',
      key: 'isNew',
      render: (isNew, record) => (
          <Switch
              checked={isNew}
              onChange={(checked) => handleSwitchChange(record.id, 'isNew', checked)}
          />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
          <Space size="middle">
            <a onClick={() => navigate('/product/edit/' + record.id)}>修改</a>
            <a onClick={() => handleDelete(record.id)}>删除</a>
          </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchProductList(pagination.current, pagination.pageSize);
  }, [pagination.current, pagination.pageSize]);

  // const fetchProductList = (page, pageSize) => {
  //   // 获取商品列表示例
  //   getProductList({ page: 1, pageSize: 10 }).then(response => {
  //     if (response && response.result) {
  //       console.log('Product List:', response.result);
  //       setList(response.result);
  //     } else {
  //       console.error('Error fetching product list: Invalid response');
  //     }
  //   }).catch(error => {
  //     console.error('Error fetching product list:', error);
  //   });
  //
  // };

  const fetchProductList = (page, pageSize) => {
    getProductList({ page, pageSize }).then(response => {
      if (response && response.result) {
        console.log('Product List:', response.result);
        setList(response.result);
        setPagination(prevPagination => ({
          ...prevPagination,
          current: page, // Update current page
          total: response.total, // Update total count
        }));
      } else {
        console.error('Error fetching product list: Invalid response');
      }
    }).catch(error => {
      console.error('Error fetching product list:', error);
    });
  };


  const handleClick = () => {
    navigate('/product/add');
  };

  const handleDelete = (id) => {
    confirm({
      title: '确认删除吗',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return deleteProduct(id).then((response) => {
          const { code, msg } = response;
          if (code === 1) {
            message.success(msg);
            fetchProductList(pagination.current, pagination.pageSize);
          }
        });
      },
    });
  };

  const handleSwitchChange = (id, key, checked) => {
    const updatedList = list.map(item => {
      if (item.id === id) {
        return { ...item, [key]: checked };
      }
      return item;
    });
    setList(updatedList);

    // Call the update API
    const productToUpdate = updatedList.find(item => item.id === id);
    updateProduct(id, productToUpdate).then(response => {
      const { code, msg } = response;
      if (code === 1) {
        message.success(msg);
      }
    });
  };

  const handleTableChange = (pagination) => {
    setPagination({
      current: pagination.current,
      pageSize: pagination.pageSize,
      total: pagination.total,
    });
  };
  // 根据搜索关键词过滤数据


  return (
      <>
        <div className="addButtonContainer" style={{height:40,}}>
          {/* 新增按钮 */}
          <PlusOutlined className="addIcon"/>
          <span className="addText">商品管理</span>
          {/* 搜索框 */}
          <Input
              placeholder="搜索商品名称"
              prefix={<SearchOutlined/>}
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              style={{width: 300, marginLeft: 20}}
          />
          {/* 新增按钮 */}
          <Button type="primary" onClick={handleClick} style={{marginBottom: 15}}>
            新增
          </Button>
        </div>

        <Table
            rowKey="id"
            dataSource={list}
            columns={columns}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
            }}
            onChange={handleTableChange}
        />
      </>
  );
}
